<script setup lang="ts">
import { ref, watch } from 'vue';
import type { QuestionItem } from '#/types/question';
import QuestionHeader from './question-header.vue';
import { QUESTION_STATUS } from '../../const';
import { $t } from '@vben/locales';
interface Props {
  question: QuestionItem;
  questionIndex: number;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  updateStatus: [questionItem: QuestionItem, status: typeof QUESTION_STATUS.ANSWERED | typeof QUESTION_STATUS.UNANSWERED | typeof QUESTION_STATUS.MARKED,isMarked?:boolean];
  updateAnswer: [questionId: string | number, answer: string];
}>();

const answerText = ref<string>('');
const isMarked = ref(false);

// 初始化答案和状态
watch(() => props.question, (newQuestion) => {
  if (newQuestion.answer) {
    answerText.value = newQuestion.answer as string;
  }
  isMarked.value = newQuestion.markDoubtful || false;
}, { immediate: true });

// 处理答案变化
const handleAnswerChange = () => {
  emit('updateAnswer', props.question.id, answerText.value);
  const status = answerText.value.trim() ? QUESTION_STATUS.ANSWERED : QUESTION_STATUS.UNANSWERED;
  emit('updateStatus', props.question, status,isMarked.value);
};

// 处理存疑操作
const handleMark = () => {
  isMarked.value = !isMarked.value;
  const status = isMarked.value ? QUESTION_STATUS.MARKED : (answerText.value.trim() ? QUESTION_STATUS.ANSWERED : QUESTION_STATUS.UNANSWERED);
  emit('updateStatus', props.question, status,isMarked.value);
};
</script>

<template>
  <div class="essay-question pb-4" :data-question-id="question.id">
    <QuestionHeader 
      :question-index="questionIndex"
      :stem="question.originalData?.stem || ''"
      :score="question.originalData?.score || 0"
      :is-marked="isMarked"
      @mark="handleMark"
    />
    
    <!-- <div v-if="question.originalData?.stemImg" class="question-image mb-4">
      <img :src="question.originalData.stemImg" :alt="$t('examCore.questionImage')" class="max-w-full h-auto" />
    </div> -->

    <div class="answer-area ml-4">
      <el-input
        v-model="answerText"
        type="textarea"
        :rows="8"
        :placeholder="$t('examCore.questions.answerInDetail')"
        @change="handleAnswerChange"
        class="w-full"
        show-word-limit
        maxlength="2000"
      />
    </div>
  </div>
</template>

<style scoped>
.answer-area {
  margin-top: 16px;
}
</style> 
